package Client;

import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Date;

import javax.swing.JTable;

import DBUtil.UserInfo;
import GroupWare.ShareRoot;
import Tools.IMG;
import Tools.Log;
import Windows.AboutWindow;
import Windows.MainWindows;
import Windows.Search.ResSearchTable;
import Windows.ShowWindows.ShowLoginWindow;
import Windows.ShowWindows.ShowWindow;
import XML.XML;
import XML.XMLNode;

/**
 * 客户端管理类 继承C>S客户线程
 * 
 * @author Administrator
 * 
 */
public class ClientManager extends ClientThread implements msgSend, ClientListener {
	UserInfo userinfo;
//	public static DBHandle dbh = new DBHandle();
	public ClientServer fs = new ClientServer();// 服务
	public ShareRoot sp;// 共享目录

	public String userid;// 用户名（共享一个指向）
	public String pwd;// 登陆密码

	/**
	 * 构造方法
	 * 
	 * @param address
	 *            服务器地址
	 * @param port
	 *            端口号
	 * @throws IOException
	 * @throws UnknownHostException
	 */
	public ClientManager(String address, int port, File shareDir) throws UnknownHostException, IOException {
		super(address, port);
		sp = new ShareRoot(shareDir);// 生成共享文件列表
		fs.addListener(sp);
		this.addClientListenser(this);
		this.addClientListenser(sp);

		StartConn();// 连接服务端

	}

	@Override
	public void addFellow(String userID, String msg) {
		// TODO Auto-generated method stub

	}

	/**
	 * 申请添加好友通过事件
	 * 
	 * @param msg
	 */
	public void allowFellow(String userID, XML msg) {
		log("[申请好友]user:" + userID + " cmd:" + msg);
	}

	@Override
	public void closeSeach(JTable tab) {
		// TODO Auto-generated method stub

	}

	/**
	 * 被强迫下线
	 * 
	 * @param msg
	 */
	public void drop(XML msg) {
		log("[被迫下线]" + msg);
		System.out.println("[强迫下线]帐号在其他地方登陆！对方IP：" + msg.get("address"));
	}

	public void log(String log) {
		System.out.println("[" + new Date() + "] " + log);
	}

	@Override
	public boolean login(String userid, String pwd) {
		this.userid = userid == null ? "*" : userid;
		this.pwd = pwd == null ? "" : pwd;

		/* ---验证登陆开始--- */
		StringBuffer cmd = new StringBuffer();
		cmd.append("<Login userid=\"");
		cmd.append(userid);
		cmd.append("\" password=\"");
		cmd.append(pwd);
		cmd.append("\" sport=\"");
		cmd.append(fs.s.getLocalPort());
		cmd.append("\" inet=\"Outer net\" />");

		Log.print("[SEND]C>S Login,  Cmd:" + cmd);

		send(cmd);// 发送登陆请求
		return true;
		/* ---验证登陆结束--- */
	}

	/**
	 * 好友消息事件
	 * 
	 * @param msg
	 */
	public void message(String userID, XML msg) {
		log("[好友消息]" + msg);
	}

	@Override
	public void onCloseEvent(CloseEvent cce) {

	}

	@Override
	public void onMsgEvent(MsgEvent ce) {
		String cmd = ce.getCmd().FLAG;
		if (cmd.equalsIgnoreCase("OK")) {
			userinfo = new UserInfo(ce.getCmd().get("userid"), Integer.parseInt(ce.getCmd().get("integral")), Integer.parseInt(ce.getCmd().get("grade")), Long.parseLong(ce.getCmd().get("online_time")));

			if (userinfo != null) {
				if (MainWindows.getInstance().isVisible() == false) {
					ShowWindow.stopWindow(AboutWindow.getAboutWindow());
					MainWindows.getInstance().setVisible(true);
					AboutWindow.getAboutWindow().doFinish();
				}
				ShowLoginWindow ssw = new ShowLoginWindow(IMG.LOGIN_BG, IMG.LOGIN_BG2);
				ssw.setSize(256, 180);
				ssw.jlTitle.setText("恭喜,登陆成功！");
				// jl.setHorizontalAlignment(JLabel.CENTER);
				ssw.jl1.setText("　　用户名称: " + this.userid);
				ssw.jl2.setText("　　用户类型: " + (this.userid.equals("*") ? "匿名用户" : "注册用户"));
				ssw.jl4.setText(userinfo != null ? "　　当前积分: " + userinfo.getInteger() : "");
				ssw.jl3.setText(userinfo != null ? "　　会员等级: " + userinfo.getGrade() : "");
				ssw.jlICO.setIcon(IMG.MESSAGE_ICON);
				ssw.start();

				new Thread() {
					@Override
					public void run() {
						while (isConnected()) {
							try {
								Thread.sleep(1000);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
							send("<pulse />");
						}
					}
				}.start();
			}
			MainWindows.loginWindows.jtfUserName.setText("");
			MainWindows.loginWindows.jPasswordField1.setText("");
			MainWindows.jpWeast.setUser(userinfo);

		} else if (cmd.equals("NO")) {
			// this.StartConn();//重新连接
			ShowLoginWindow ssw = new ShowLoginWindow(IMG.LOGIN_E_BG, IMG.LOGIN_E_BG2);
			ssw.setSize(256, 170);
			ssw.jlTitle.setText("对不起,用户名或密码不正确！");
			// jl.setHorizontalAlignment(JLabel.CENTER);

			ssw.jl1.setText("");
			ssw.jl2.setText("");
			ssw.jl3.setText("");
			ssw.jl4.setText("");
			ssw.jlICO.setIcon(IMG.MESSAGE_ICON2);
			ssw.start();
			// MainWindows.jpWeast.setUser(userinfo);

			if (MainWindows.getInstance().isVisible() == false) {
				ShowWindow.stopWindow(AboutWindow.getAboutWindow());
				MainWindows.getInstance().setVisible(true);
				AboutWindow.getAboutWindow().doFinish();
			}
		}
	}

	@Override
	public void seach(String keys, int minSize, int maxSize, String type, ResSearchTable tbl) {
	}

	@Override
	public void sendGetRes(String md5) {
		// TODO Auto-generated method stub
		send("<GET md5='" + md5 + "'/>");
	}

	/**
	 * 发送群消息
	 * 
	 * @param id
	 *            群编号
	 * @param msg
	 *            消息内容
	 * @return
	 */
	@Override
	public boolean sendGroupMessage(int id, String msg) {
//		if (!dbh.groupIn(id, user)) {
//			return false;
//		}
		XMLNode cd = new XMLNode(null, "GroupMsg");
		cd.put("id", String.valueOf(id));
		cd.setData(msg);
		send(cd);
		return true;
	}

	@Override
	public void sendMessage(String UserID, String msg) {
		// TODO Auto-generated method stub

	}

	/**
	 * 连接服务端
	 */
	public void StartConn() {
		Log.print("Starting Connection Server ..." + getPip());
		new Thread() {

			@Override
			public void run() {
				for(;true;){
					if(isConnected()==false){
						AboutWindow.getAboutWindow().setMessage("正在登录...");
						Connect();
					}
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();
	}

	/**
	 * 系统消息触发事件
	 * 
	 * @param msg
	 */
	public void sysMsg(XML msg) {
		log("[系统消息]" + msg);
	}

}
